<?php
namespace App\Library\Impl;
use App\Library\RepotsLibraryInterFace;
use App\Models\DawnOss;
use Dflydev\DotAccessData\Util;
use Illuminate\Support\Facades\Log;
use App\Library\UserLibraryInterface;
use Carbon\Carbon;
use Illuminate\Support\Facades\Hash;
use App\Pojo\ResponsePojo;
use App\Library\ZhjyLibraryInterface;
use Illuminate\Support\Facades\Auth;
use App\Models\DawnZhjyUser;
use App\Models\ZhjyRepot;
use App\Library\FileLibraryInterFace;
use function PHPUnit\Framework\isEmpty;
use App\Utils\Utils;
use Illuminate\Support\Facades\DB;
class RepotsLibraryImpl implements RepotsLibraryInterFace{

    private $fileLibrary;
    public function __construct(FileLibraryInterFace $fileLibrary)
    {
        $this->fileLibrary = $fileLibrary;
    }

    public function insertReport(array $credentials){

        $successCount = 0;
        $failCount = 0;
        $totalCount = count($credentials);

        foreach($credentials as $item){
            try {
                $reportBody = [
                    'user_id' => Auth::id(),
                    'recordType' => $item['recordType'],
                    'todaySummary' => $item['todaySummary'],
                    'nextSummary' => $item['nextSummary'],
                    'feedback' => $item['feedback'],
                    'selfEvaluate' => $item['selfEvaluate'],
                    'filePath' => $item['filePath'],
                    'fileName' => $item['fileName'],
                    'isdelete' => 1
                ];
                ZhjyRepot::create($reportBody);
                $successCount++;
            } catch (\Exception $e) {
                Log::error('插入报告失败: ' . $e->getMessage());
                $failCount++;
            }
        }
        
        Log::info('插入报告成功: ' . $successCount . '条，失败: ' . $failCount . '条，总计: ' . $totalCount . '条');
        return [
            'successCount' => $successCount,
            'failCount' => $failCount,
            'totalCount' => $totalCount
        ];
        
    }

    public function getZhjyRepots($credentials){
        return ZhjyRepot::where('user_id', Auth::id())
            ->where('isdelete', 1)
            ->orderBy('created_at', 'desc')
            ->paginate($credentials['pageSize'], ['*'], 'page', $credentials['currentPage']);
    }

    public function updateZhjyRepots($credentials){
        DB::beginTransaction();
        try {
            
            $credentials['oldFiles'] = $this->fileListCavnId($credentials['oldFiles']);
            $credentials['oldImages'] = $this->imageListCavnId($credentials['oldImages']);
            $credentials['newImages'] = $this->imageListCavnId($credentials['newImages']);
            $credentials['newFiles'] = $this->imageListCavnId($credentials['newFiles']);
            $delHashs = [];
            foreach($credentials['oldFiles'] as $item){
                $delHashs[] = $item;
            }
            
            foreach($credentials['oldImages'] as $item){
                $delHashs[] = $item;
            }
    
            $this->fileLibrary->deleteFileByHashsStatus($delHashs);
    
           $allFiles = array_merge($credentials['oldFiles'], $credentials['oldImages'], $credentials['newImages'], $credentials['newFiles']);
            $allFileHashs = [];
            foreach($allFiles as $item){
                $allFileHashs[] = $item;
            }
            
            Log::info('allFiles===========================');
            Log::info(implode(',', $allFileHashs));
            Log::info('allFiles===========================');
           $updatebody = [
                'id' => $credentials['id'],
                'todaySummary' => $credentials['todaySummary'],
                'nextSummary' => $credentials['nextSummary'],
                'feedback' => $credentials['feedback'],
                'recordType' => $credentials['recordType'],
                'selfEvaluate' => Utils::HtmlToCvanSelfEvaluate($credentials['selfEvaluate']),
                'fileId' => implode(',', $allFileHashs)
            ];
            
            // Log::info('更新报告===========================');
    
            $this->fileLibrary->rowbackFileByHashsStatus($delHashs);
            ZhjyRepot::where('id', $credentials['id'])
            ->update($updatebody);
            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            Log::error('更新报告失败: ' . $e->getMessage());
            throw $e;
        }

        
    }

    public function imageListCavnId($images){
        $ids = [];
        if(count($images) > 0){
            foreach($images as $item){
                $ids[] = $item['file_hash'];
            }
        }
        return  $ids;
    }
    public function fileListCavnId($files){
        $ids = [];
        if(count($files) > 0){
            foreach($files as $item){
                $ids[] = $item['file_hash'];
            }
        }
        return $ids;
    }

    public function getRepotsBylogId($logId){
        return ZhjyRepot::select('*')
            ->where('id', $logId)
            ->where('isdelete', 1)
            ->get();
    }
  

    public function deleteZhjyRepots($credentials){
       if($credentials['ids'] == 'all'){
        Log::error('用户id: '.Auth::user()->id);
            ZhjyRepot::where('user_id', Auth::id())
            ->update(['isdelete' => 2]);
       }else{
            ZhjyRepot::whereIn('id', $credentials['ids'])
            ->update(['isdelete' => 2]);
       }
    }
}